import { ref, computed } from 'vue'
import { supabase } from '../../lib/supabase'
import type { Movie, MovieType, MovieFilters, MovieLoadRequest, CacheItem } from './types'
import { useUiStore } from '../../store/useUiStore'

// 缓存系统
const movieCache = new Map<string, CacheItem<Movie[]>>()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 批量加载状态管理
const globalLoadingState = ref({
  isLoading: false,
  loadingTypes: new Set<string>()
})

export const useMovieLoader = () => {
  const uiStore = useUiStore()
  // 基础加载状态
  const isLoading = ref(false)
  const hasMore = ref(true)
  const lastLoadedId = ref<number | null>(null)
  
  // 电影数据状态
  const movies = ref<Movie[]>([])
  const error = ref<string | null>(null)

  // 生成缓存键
  const getCacheKey = (type: MovieType, count: number, offset: number = 0, filters?: MovieFilters) => {
    if (filters) {
      const filterStr = JSON.stringify(filters)
      return `${type}_${count}_${offset}_${filterStr}`
    }
    return `${type}_${count}_${offset}`
  }

  // 检查缓存是否有效
  const isCacheValid = (cacheKey: string) => {
    const cached = movieCache.get(cacheKey)
    if (!cached) return false
    return Date.now() - cached.timestamp < CACHE_DURATION
  }

  // 从缓存获取数据
  const getFromCache = (cacheKey: string): Movie[] | null => {
    if (isCacheValid(cacheKey)) {
      const cached = movieCache.get(cacheKey)!.data
      console.log(`Cache hit for ${cacheKey}:`, cached.length, 'movies')
      return cached
    }
    console.log(`Cache miss for ${cacheKey}`)
    return null
  }

  // 设置缓存
  const setCache = (cacheKey: string, data: Movie[]) => {
    movieCache.set(cacheKey, {
      data,
      timestamp: Date.now()
    })
  }

  // 应用筛选条件
  const applyFilters = (query: any, filters: MovieFilters) => {
    // 按艺术类型筛选
    if (filters.genre && filters.genre !== 'all') {
      // 使用标签系统筛选
      query = query.contains('genres', [filters.genre])
    }

    // 按平行宇宙设定筛选
    if (filters.universe && filters.universe !== 'all') {
      // movies_view 中的 universe 为数组
      query = query.contains('universe', [filters.universe])
    }

    // 按语言筛选
    if (filters.language && filters.language !== 'all') {
      // movies_view 中的 language 为数组
      query = query.contains('language', [filters.language])
    }

    // 按国家/地区筛选
    if (filters.country && filters.country !== 'all') {
      // movies_view 中的 country 为数组
      query = query.contains('country', [filters.country])
    }

    // 按AI生成筛选
    if (filters.ai && filters.ai !== 'all') {
      query = query.eq('is_ai', filters.ai === 'ai')
    }

    return query
  }

  // 批量加载电影数据
  const batchLoadMovies = async (requests: MovieLoadRequest[]): Promise<Map<string, Movie[]>> => {
    const results = new Map<string, Movie[]>()
    
    // 检查缓存，只加载未缓存的数据
    const uncachedRequests = requests.filter(req => {
      const cacheKey = getCacheKey(req.type, req.count, req.offset || 0, req.filters)
      const cached = getFromCache(cacheKey)
      if (cached) {
        results.set(cacheKey, cached)
        return false
      }
      return true
    })

    if (uncachedRequests.length === 0) {
      return results
    }

    // 构建批量查询
    const queries = uncachedRequests.map(req => {
      let query = supabase
        .from('movies_view')
        .select('id, title, cover_url, rating, user_tags, is_ai, year, views, updated_at, description, genres, universe, language, country')
        .limit(req.count)

      switch (req.type) {
        case 'carousel':
          query = query.order('rating', { ascending: false })
          break
        case 'hot':
          query = query.order('views', { ascending: false })
          break
        case 'masonry':
          query = query.order('created_at', { ascending: false })
          if (req.offset && req.offset > 0) {
            query = query.range(req.offset, req.offset + req.count - 1)
          }
          console.log(`Masonry query: count=${req.count}, offset=${req.offset || 0}, type=${req.type}`)
          break
        case 'category':
          // 应用筛选条件
          if (req.filters) {
            query = applyFilters(query, req.filters)
          }
          if (req.offset && req.offset > 0) {
            query = query.range(req.offset, req.offset + req.count - 1)
          }
          break
      }

      // 全局 AI 内容过滤
      if (uiStore.filterAiContent) {
        query = query.eq('is_ai', false)
      }
      return { query, request: req }
    })

    // 并行执行查询
    const promises = queries.map(async ({ query, request }) => {
      try {
         const { data, error } = await query
        if (error) {
          console.error(`Error loading ${request.type} movies:`, error)
          return { key: getCacheKey(request.type, request.count, request.offset || 0, request.filters), data: [] }
        }

         const movies: Movie[] = data.map(movie => ({
          id: movie.id,
          coverUrl: movie.cover_url,
          title: movie.title,
          rating: movie.rating,
           tags: movie.user_tags || [],
          isAi: movie.is_ai,
           genres: movie.genres || [],
           universe: Array.isArray(movie.universe) ? movie.universe[0] : movie.universe,
           language: Array.isArray(movie.language) ? movie.language[0] : movie.language,
           year: movie.year,
           country: Array.isArray(movie.country) ? movie.country[0] : movie.country,
          views: movie.views,
          updatedAt: movie.updated_at,
          description: movie.description
        }))

        // 设置缓存
        const cacheKey = getCacheKey(request.type, request.count, request.offset || 0, request.filters)
        setCache(cacheKey, movies)

        return { key: cacheKey, data: movies }
      } catch (error) {
        console.error(`Error in batch load for ${request.type}:`, error)
        return { key: getCacheKey(request.type, request.count, request.offset || 0, request.filters), data: [] }
      }
    })

    const batchResults = await Promise.all(promises)
    batchResults.forEach(({ key, data }) => {
      results.set(key, data)
    })

    return results
  }

  // 加载电影列表
  const loadMovies = async (count: number, type: MovieType, offset: number = 0, filters?: MovieFilters): Promise<Movie[]> => {
    const cacheKey = getCacheKey(type, count, offset, filters)
    
    // 检查缓存
    const cached = getFromCache(cacheKey)
    if (cached) {
      return cached
    }

    isLoading.value = true
    
    try {
      let query = supabase
        .from('movies_view')
        .select('id, title, cover_url, rating, user_tags, is_ai, year, views, updated_at, description, genres, universe, language, country')
        .limit(count)

      // 根据类型调整查询
      switch (type) {
        case 'carousel':
          // 轮播显示评分最高的电影
          query = query.order('rating', { ascending: false })
          break
        case 'hot':
          // 热门电影按观看量排序
          query = query.order('views', { ascending: false })
          break
        case 'masonry':
          // 瀑布流按最新排序，支持分页
          query = query.order('created_at', { ascending: false })
          if (offset > 0) {
            query = query.range(offset, offset + count - 1)
          }
          break
        case 'category':
          // 分类查询，应用筛选条件
          if (filters) {
            query = applyFilters(query, filters)
          }
          // 添加排序
          query = query.order('created_at', { ascending: false })
          if (offset > 0) {
            query = query.range(offset, offset + count - 1)
          }
          break
      }

      // 全局 AI 内容过滤
      if (uiStore.filterAiContent) {
        query = query.eq('is_ai', false)
      }

      const { data, error } = await query

      if (error) {
        console.error('Error loading movies:', error)
        return []
      }

      // 转换数据格式
      const movies: Movie[] = data.map(movie => ({
        id: movie.id,
        coverUrl: movie.cover_url,
        title: movie.title,
        rating: movie.rating,
        tags: movie.user_tags || [],
        isAi: movie.is_ai,
        genres: movie.genres || [],
        universe: Array.isArray(movie.universe) ? movie.universe[0] : movie.universe,
        language: Array.isArray(movie.language) ? movie.language[0] : movie.language,
        year: movie.year,
        country: Array.isArray(movie.country) ? movie.country[0] : movie.country,
        views: movie.views,
        updatedAt: movie.updated_at,
        description: movie.description
      }))

      // 设置缓存
      setCache(cacheKey, movies)

      isLoading.value = false
      return movies
    } catch (error) {
      console.error('Error loading movies:', error)
      isLoading.value = false
      return []
    }
  }

  // 加载随机电影
  const loadRandomMovies = async (excludeId: number, count: number = 6): Promise<Movie[]> => {
    try {
      console.log(`Loading ${count} random movies, excluding ID: ${excludeId}`)
      
      // 使用 PostgreSQL 的随机排序功能
      let query = supabase
        .from('movies')
        .select('id, title, cover_url, rating, tags, is_ai')
        .neq('id', excludeId)
        .order('id', { ascending: false }) // 临时使用id排序，避免random()语法错误
        .limit(count)

      if (uiStore.filterAiContent) {
        query = query.eq('is_ai', false)
      }

      const { data, error } = await query

      if (error) {
        console.error('Error loading random movies:', error)
        return []
      }

      console.log(`Found ${data?.length || 0} random movies`)

      // 转换数据格式
      const randomMoviesData: Movie[] = (data || []).map(movie => ({
        id: movie.id,
        coverUrl: movie.cover_url,
        title: movie.title,
        rating: movie.rating,
        tags: movie.tags || [],
        isAi: movie.is_ai
      }))
      
      return randomMoviesData
    } catch (error) {
      console.error('Error loading random movies:', error)
      return []
    }
  }

  // 加载用户上传的电影
  const loadUserMovies = async (userId: string, limit: number = 12, offset: number = 0): Promise<Movie[]> => {
    try {
      console.log(`Loading ${limit} movies for user ${userId}, offset: ${offset}`)
      
      let query2 = supabase
        .from('movies_view')
        .select('id, title, cover_url, rating, user_tags, is_ai, year, views, updated_at, description, genres, universe, language, country')
        .eq('uploader_id', userId)
        .order('created_at', { ascending: false })
        .range(offset, offset + limit - 1)

      if (uiStore.filterAiContent) {
        query2 = query2.eq('is_ai', false)
      }

      const { data, error } = await query2

      if (error) {
        console.error('Error loading user movies:', error)
        return []
      }

      console.log(`Found ${data?.length || 0} movies for user ${userId}`)

      // 转换数据格式
      const userMovies: Movie[] = (data || []).map(movie => ({
        id: movie.id,
        coverUrl: movie.cover_url,
        title: movie.title,
        rating: movie.rating,
        tags: movie.user_tags || [],
        isAi: movie.is_ai,
        genres: movie.genres || [],
        universe: Array.isArray(movie.universe) ? movie.universe[0] : movie.universe,
        language: Array.isArray(movie.language) ? movie.language[0] : movie.language,
        year: movie.year,
        country: Array.isArray(movie.country) ? movie.country[0] : movie.country,
        views: movie.views,
        updatedAt: movie.updated_at,
        description: movie.description
      }))
      
      return userMovies
    } catch (error) {
      console.error('Error loading user movies:', error)
      return []
    }
  }

  // 重置加载状态
  const resetLoader = () => {
    hasMore.value = true
    lastLoadedId.value = null
  }

  // 清除缓存
  const clearCache = () => {
    movieCache.clear()
  }

  // 预加载热门数据
  const preloadHotMovies = async () => {
    const cacheKey = getCacheKey('hot', 12, 0)
    if (!isCacheValid(cacheKey)) {
      await loadMovies(12, 'hot', 0)
    }
  }

  return {
    // 状态
    isLoading,
    hasMore,
    movies,
    error,
    
    // 方法
    loadMovies,
    batchLoadMovies,
    loadRandomMovies,
    loadUserMovies,
    resetLoader,
    clearCache,
    preloadHotMovies,
    
    // 缓存方法
    getCacheKey,
    isCacheValid,
    getFromCache,
    setCache
  }
}
